import { PageContainer,TableDropdown,ProTable } from '@ant-design/pro-components';
import { driverList,driverRemove } from '@/services/driver';
import { Button, Dropdown, Space, Tag, message } from 'antd';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { EllipsisOutlined, PlusOutlined } from '@ant-design/icons';
import { useRef,useState } from 'react';
import { history } from '@umijs/max';



export const waitTimePromise = async (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const actionAdd = async (id: string) => {
  const actionType: string = id === '0' ? 'edit' : 'view';
  history.push({
    pathname: '/driver/driverAdd?actionType='+ actionType +'&fid=' + id,
  });
  const time = 100;
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export const waitTime = async (time: number = 100) => {
  await waitTimePromise(time);
};
const DriverList: React.FC = () => {
  const [selectedRowsState, setSelectedRows] = useState<DriverAPI.Driver[]>([]);
  const actionRef = useRef<ActionType>();

  /**
 *  Delete node
 * @zh-CN 删除节点
 *
 * @param selectedRows
 */
const handleRemove = async (selectedRows: DriverAPI.Driver[]) => {
  const hide = message.loading('正在删除');
  const token =  localStorage.getItem('token') + "";
  if (!selectedRows) return true;
  console.log("selectedRows",selectedRows.map((row) => row.fid));
  console.log("selectedRowsStr",selectedRows.map((row) => row.fid + ""));
  
  // try {
  //   const queryInfoParams: DriverAPI.QueryInfoParams = {
  //     fid: selectedRows.map((row) => row.key),
  //     token: token,
  //   }
  //   await driverRemove({
  //     fid: selectedRows.map((row) => row.key),
  //   });
  //   hide();
  //   message.success('Deleted successfully and will refresh soon');
  //   return true;
  // } catch (error) {
  //   hide();
  //   message.error('Delete failed, please try again');
  //   return false;
  // }
};

  async function actionRemove(fid: string) {
    const hide = message.loading('正在删除');
    
    const token =  localStorage.getItem('token') + "";
    const queryInfoParams: DriverAPI.QueryInfoParams = {
      fid: fid,
      token: token,
    }
    const result = await driverRemove(queryInfoParams);
    if(result.code === 200){
      if(result.data.fcode === "true"){
        message.success('删除成功');
        actionRef.current?.reload();
        hide();
      }else{
        message.error('删除失败');
        hide();
      }
    } 
  };


  const columns: ProColumns<DriverAPI.GithubIssueItem>[] = [
    {
      dataIndex: 'fid',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '身份证号',
      dataIndex: 'fidcard',
      copyable: true,
      ellipsis: true,
      tip: '标题过长会自动收缩',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '此项为必填项',
          },
        ],
      },
    },
    {
      disable: true,
      title: '姓名',
      copyable: true,
      dataIndex: 'fname',
      filters: true,
      // onFilter: true,
      ellipsis: true,
    },
    {
      disable: true,
      title: '手机号',
      dataIndex: 'fmobile'
    },
    {
      title: '从业资格证',
      key: 'showTime',
      dataIndex: 'fcertificate',
      sorter: true,
      hideInSearch: true,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      render: (text, record, _, action) => [    
        <a
          key="editable"
          onClick={() => {
            console.log(_,record);
            actionAdd(record.fid);
          }}
        >
          查看
        </a>,
        <a key="remove"
          onClick={() => {
            console.log(record);
            actionRemove(record.fid);  
          }}
        >
          删除
        </a>
      ],
    },
  ];
  return (
    <PageContainer>
      <ProTable<DriverAPI.Driver, DriverAPI.QueryParams>
        // params 是需要自带的参数
        // 这个参数优先级更高，会覆盖查询表单的参数
        rowSelection={{
          onChange: (_, selectedRows) => {
            console.log("selectedRows",selectedRows);
            setSelectedRows(selectedRows);
          },
        }}
        columns={columns}
        actionRef={actionRef}
        cardBordered
        request={async (params, sorter, filters) => {
          // 这里需要返回一个 Promise,在返回之前你可以进行数据转化
          // 如果需要转化参数可以在这里进行修改
          const msg = await driverList({
            username: params.username,
            pageSize: params.pageSize,
            current: params.current,
            token: localStorage.getItem('token') + "",
            query: params,
          });
          return {
            data: msg.data,
            // success 请返回 true，
            // 不然 table 会停止解析数据，即使有数据
            success: msg.code == 200 ? true : false,
            // 不传会使用 data 的长度，如果是分页一定要传
            // total: number,
          };
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
          onChange(value) {
            console.log('value: ', value);
          },
        }}
        rowKey="fid"
        search={{
          labelWidth: 'auto',
        }}
        options={{
          setting: {
            listsHeight: 400,
          },
        }}
        toolBarRender={() => [
          <Button key="actionAdd" icon={<PlusOutlined />} type="primary"
            onClick={() => {
              actionAdd("0");
            }}  
          >
            新建
          </Button>,
          <Button key="actionRemoveAll" icon={<PlusOutlined />} type="primary"
          onClick={() => {
              handleRemove(selectedRowsState);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
          }}  
        >
          删除全部
        </Button>
          
          
        ]}
      />
    </PageContainer>
  )
}

export default DriverList;